package com.example.demo.web.services;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.async.DeferredResult;

import com.example.demo.web.Entity.OrganizationEntity;
import com.example.demo.web.Entity.UserEntity;
import com.example.demo.web.Entity.UserLogEntity;
import com.example.demo.web.Entity.UserOperLogEntity;
import com.example.demo.web.dao.LogDAO;
import com.example.demo.web.util.ReadExcel;
import com.example.demo.web.util.XinLongUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;


@Service
public class LogUionService {
	private LogDAO userlogDao;
	
	@Autowired
	public void setLogDAO(LogDAO userlogDao) {
		this.userlogDao = userlogDao;
	}	
	
	public void _getUserManagerLogs(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request,HttpSession session) throws JsonProcessingException{
		UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
		String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();
    	int pageNumber = 0;
		int pageSize = 0;
		String start = "";
		String end = "";
		String searchval = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			pageNumber =rootNode.get("pageNumber").asInt();
			pageSize =rootNode.get("pageSize").asInt();
			start =rootNode.get("start").asText();
			end =rootNode.get("end").asText();
			searchval =rootNode.get("orgname").asText();
			if(start.compareTo(end) == 1){
				resjson.put("status", "2");
				resjson.put("desc", "起始日期需小于结束日期!");
				deferredResult.setResult(mapper.writeValueAsString(resjson));
				return;
			}
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
			Date dd = sdf2.parse(end);
			Calendar c = Calendar.getInstance();  
            c.setTime(dd);  
            c.add(Calendar.DAY_OF_MONTH, 1);              
            dd = c.getTime();
            end = sdf2.format(dd);
		} catch (Exception e1) {
			resjson.put("status", "2");
			resjson.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		/*resjson = XinLongUtil.OptAuth("",jsonstr, sentity);
		if(!resjson.get("status").asText().equals("1210")){
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}*/
		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		/*UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("查询人员变更记录");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setMethod("_getUserManagerLogs");
		ulog.setOrgid(sentity.getOrg_id());*/
		List<OrganizationEntity> suborgs = userlogDao.findSubOrg(sentity.getOrg_id());
		List<UserOperLogEntity> logs = null;
		int precount = 0;
		if(suborgs != null && suborgs.size() > 0){
			logs =userlogDao.findUserManagerSubAll(pageNumber,pageSize,start,end,searchval,suborgs);
			precount = userlogDao.getumlogSubCount(start,end,searchval,suborgs);
    	}
    	//List<UserOperLogEntity> logs = userlogDao.findUserManagerAll(pageNumber,pageSize,start,end,searchval);
    	ArrayNode rootnode = mapper.createArrayNode();
    	if(logs.size() > 0){
    		ObjectNode tjson = null;
    		for(UserOperLogEntity log : logs){
    			tjson = mapper.createObjectNode();
    			tjson.put("descriptor", log.getDescriptor());
    			tjson.put("orgname", log.getOrgname());
    			tjson.put("rname", log.getRname());
    			tjson.put("username", log.getUsername());
    			tjson.put("createtime", log.getCreatetime());
    			tjson.put("checkname", log.getCheckname());
    			tjson.put("operator", log.getOperator());
    			rootnode.add(tjson);
        	}
    	}
    	resjson.put("status", "1");
    	resjson.put("total", precount);
    	if(sentity.getUsername().equals("hzwlprevail")){
			resjson.put("needcheck", 0);
		}else{
			resjson.put("needcheck", XinLongUtil.isNeedCheck("系统管理/日志管理/日志导出"));
		}
    	resjson.put("pageSize", pageSize);
    	resjson.put("datas", rootnode);
		resjson.put("desc", "成功!");
		//ulog.setProceed("操作成功");
		//XinLongUtil.saveUserLog(ulog);
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
	}
	
	public void _usersyslogquery(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request,HttpSession session) throws JsonProcessingException{
		UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
		String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();
    	int pageNumber = 0;
		int pageSize = 0;
		String start = "";
		String end = "";
		String searchval = "";
		String searchproperty = "";
		String orgid = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			pageNumber =rootNode.get("pageNumber").asInt();
			pageSize =rootNode.get("pageSize").asInt();
			start =rootNode.get("start").asText();
			end =rootNode.get("end").asText();
			searchval =rootNode.get("searchval").asText();
			searchproperty =rootNode.get("searchproperty").asText();
			orgid =rootNode.get("orgid").asText();
			if(start.compareTo(end) == 1){
				resjson.put("status", "2");
				resjson.put("desc", "起始日期需小于结束日期!");
				deferredResult.setResult(mapper.writeValueAsString(resjson));
				return;
			}
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
			Date dd = sdf2.parse(end);
			Calendar c = Calendar.getInstance();  
            c.setTime(dd);  
            c.add(Calendar.DAY_OF_MONTH, 1);              
            dd = c.getTime();
            end = sdf2.format(dd);
		} catch (Exception e1) {
			resjson.put("status", "2");
			resjson.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		/*resjson = XinLongUtil.OptAuth("",jsonstr, sentity);
		if(!resjson.get("status").asText().equals("1210") && !resjson.get("status").asText().equals("1211")){
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}*/
		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		/*UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("查询系统记录");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setMethod("_usersyslogquery");
		ulog.setOrgid(sentity.getOrg_id());*/
		List<OrganizationEntity> suborgs = userlogDao.findSubOrg(sentity.getOrg_id());
		List<UserLogEntity> logs = null;
		int precount = 0;
		if(suborgs != null && suborgs.size() > 0){
			logs =userlogDao.findUserSysSubAll(pageNumber,pageSize,start,end,searchproperty,searchval,suborgs,orgid);
			precount = userlogDao.getsyslogSubCount(start,end,searchproperty,searchval,suborgs,orgid);
    	}
    	//List<UserOperLogEntity> logs = userlogDao.findUserManagerAll(pageNumber,pageSize,start,end,searchval);
    	ArrayNode rootnode = mapper.createArrayNode();
    	if(logs.size() > 0){
    		ObjectNode tjson = null;
    		for(UserLogEntity log : logs){
    			tjson = mapper.createObjectNode();
    			tjson.put("createtime", log.getCreatetime());
    			tjson.put("createusername", log.getCreateusername());
    			tjson.put("remote_addr", log.getRemote_addr());
    			tjson.put("rname", log.getRname());
    			tjson.put("descriptor", log.getDescriptor());
    			tjson.put("orgname", log.getOrgname());
    			rootnode.add(tjson);
        	}
    	}
    	resjson.put("status", "1");
    	resjson.put("total", precount);
    	if(sentity.getUsername().equals("hzwlprevail")){
			resjson.put("needcheck", 0);
		}else{
			resjson.put("needcheck", XinLongUtil.isNeedCheck("系统管理/日志管理/日志导出"));
		}
    	resjson.put("pageSize", pageSize);
    	resjson.put("datas", rootnode);
		resjson.put("desc", "成功!");
		//ulog.setProceed("操作成功");
		//XinLongUtil.saveUserLog(ulog);
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
	}
	
	
	public void WriteUserManagerlogToExcel(String[] titles,ServletOutputStream out,HttpSession session,String start,String end,String orgname){
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
		Date dd;
		try {
			dd = sdf2.parse(end);
			Calendar c = Calendar.getInstance();  
	        c.setTime(dd);  
	        c.add(Calendar.DAY_OF_MONTH, 1);              
	        dd = c.getTime();
	        end = sdf2.format(dd);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
        List<OrganizationEntity> suborgs = userlogDao.findSubOrg(sentity.getOrg_id());
		List<UserOperLogEntity> logs = null;

		if(suborgs != null && suborgs.size() > 0){
			logs =userlogDao.findUserManagerSubAll(start,end,orgname,suborgs);
    	}
    	
    	ReadExcel readExcel = new ReadExcel();
    	//List<CapitalEntity> cplist = capitalDao.findAll();
    	if(logs != null){
    		readExcel.writeUserManagerlogsExcel(logs, titles, out);
    	}
    }
	
	public void WriteSyslogToExcel(String[] titles,ServletOutputStream out,HttpSession session,String start,String end,String orgid,String searchval,String searchproperty){
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
		Date dd;
		try {
			dd = sdf2.parse(end);
			Calendar c = Calendar.getInstance();  
	        c.setTime(dd);  
	        c.add(Calendar.DAY_OF_MONTH, 1);              
	        dd = c.getTime();
	        end = sdf2.format(dd);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		List<OrganizationEntity> suborgs = userlogDao.findSubOrg(sentity.getOrg_id());
		List<UserLogEntity> logs = null;
		int precount = 0;
		if(suborgs != null && suborgs.size() > 0){
			logs =userlogDao.findUserSysSubAll(start,end,searchproperty,searchval,suborgs,orgid);
    	}
    	
    	ReadExcel readExcel = new ReadExcel();
    	//List<CapitalEntity> cplist = capitalDao.findAll();
    	if(logs != null){
    		readExcel.writeSyslogsExcel(logs, titles, out);
    	}
    }

}
